package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Typeface
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.tu.loadingdialog.LoadingDailog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.ClassListAdapter
import com.lancoo.znbkxx.teacher.adapter.PaperTrailListAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.AibkPaperPreviewActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FragmentAipreparationBinding
import com.lancoo.znbkxx.teacher.model.OperationHelp
import com.lancoo.znbkxx.teacher.model.data.ClassFlag
import com.lancoo.znbkxx.teacher.model.data.PaperTrailSection
import com.lancoo.znbkxx.teacher.ui.activity.BasicPaperActivity
import com.lancoo.znbkxx.teacher.ui.activity.PaperLibraryActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.MkUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.widget.AIFilterPopupWindow
import com.lancoo.znbkxx.teacher.widget.AnswerTimeEditPopupWindow
import com.lancoo.znbkxx.teacher.widget.ClassMenu
import com.lancoo.znbkxx.teacher.widget.PublishPopupWindow
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

import kotlinx.android.synthetic.main.fragment_aipreparation.*
import kotlinx.android.synthetic.main.view_edit_answer_time.view.*
import kotlinx.android.synthetic.main.view_filter_window.view.*
import paperToChaKanChengJi.CheckScoreActivity

/**
 *@author Admin
 *@date 2021/2/1
 *
 */
class AIPreparationFragment : BaseVMFragment<PaperViewModel, FragmentAipreparationBinding>(),
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener,
        View.OnClickListener, ChipGroup.OnCheckedChangeListener {
    private val paperList = mutableListOf<PaperTrailSection>()
    private val classFlagList = mutableListOf<ClassFlag>()
    private lateinit var paperAdapter: PaperTrailListAdapter
    private var position: Int = 0
    private var classPosition = 0
    private var finish: Int = -1
    private var layer: Int = -1
    private var type = 0
    private val filterPopupWindow by lazy {
        AIFilterPopupWindow(requireContext(), this, this)
    }
    private val classPopupWindow by lazy {
        val list = mutableListOf<String>()
        Ext.INFOLIST!!.forEach {
            list.add(it.CourseClassName)
        }
        ClassMenu(requireContext(), list, this)
    }
    private var timeEditWindow: AnswerTimeEditPopupWindow? = null
//    private val timeEditWindow by lazy {
//        AnswerTimeEditPopupWindow(requireContext(), this)
//    }
    private val publishWindow by lazy {
        PublishPopupWindow(classFlagList, requireContext(), this)
    }
    private val loadingDialog by lazy {
        LoadingDailog.Builder(context).setMessage("发布中...").setCancelOutside(false)
                .setCancelable(false).create()
    }
    private val editLoadingDialog by lazy {
        LoadingDailog.Builder(context).setMessage("修改中...").setCancelOutside(false)
                .setCancelable(false).create()
    }

    override fun setLayoutID(): Int {
        return R.layout.fragment_aipreparation
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        binding.model = viewModel
        tv_title.typeface = Typeface.createFromAsset(requireContext().assets,
                "fonts/cool_black.TTF")
        tv_empty.typeface = Typeface.createFromAsset(requireActivity().assets, "fonts/happy.ttf")
        tv_test.text = "${Ext.TESTNAME}复习"
        initSpinner()
        initList()
        reSet()
    }

    private fun initSpinner() {
        tv_classname.text = Ext.COURSE_CLASSNAME
        tv_classname.setOnClickListener(this)
        tv_filter.setOnClickListener(this)
        tv_textbook.setOnClickListener(this)
        tv_topic.setOnClickListener(this)
        tv_test.setOnClickListener(this)
        tv_library.setOnClickListener(this)
        tv_local.setOnClickListener(this)
    }

    private fun initList() {
        viewModel.pageNo.value = 1
        viewModel.pageSize.value = 10
        paperAdapter = PaperTrailListAdapter(R.layout.item_paper_trail_header, paperList, false)
        paperAdapter.onItemClickListener = this
        paperAdapter.onItemChildClickListener = this
        val emptyView = layoutInflater.inflate(R.layout.adapter_item_empty, null)
        paperAdapter.emptyView = emptyView
        val manager = LinearLayoutManager(requireContext())
        val hashMap = hashMapOf<String, Int>()
        hashMap[SpacesItemDecoration.BOTTOM_SPACE] = DensityUtils.dp2px(requireContext(), 12f)
        rv_paper.addItemDecoration(SpacesItemDecoration(hashMap))
        rv_paper.adapter = paperAdapter
        rv_paper.layoutManager = manager
        swipe_layout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                initEffectiveInfo()
                viewModel.pageNo.value = 1
                viewModel.pageSize.value = 10
                finish = -1
                layer = -1
                initPaper()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (viewModel.mPaperTrailInfo.value!!.Count >= viewModel.pageSize.value!!) {
                    viewModel.pageSize.value = viewModel.pageSize.value!! + 10
                    initPaper()
                }
            }
        })
    }

    override fun providerContext(): Any {
        return this
    }

    override fun providerVMClass(): Class<PaperViewModel> {
        return PaperViewModel::class.java
    }

    private fun initPaper() {
        viewModel.getMobilePaperList(Ext.COURSE_CLASSID, 1, finish, layer,
                viewModel.pageNo.value!!, viewModel.pageSize.value!!, CurrentUser.getSchoolID(),
                CurrentUser.getToken(), CurrentUser.getUserID(), "")
    }

    private fun initEffectiveInfo() {
        viewModel.getEffectivenessEvaluation(CurrentUser.getToken(), CurrentUser.getUserID(),
                Ext.COURSE_CLASSID)
    }

    private fun release(position: Int) {
//        val state = paperList[position].t.State
        val setId = paperList[position].t.SetID
        val paperId = paperList[position].t.PaperID
        val layer = paperList[position].t.Layer
        val classList = classFlagList.filter { it.checked }
        if (classList.isNullOrEmpty()) {
            MyToast.showToast("请选择发布班级")
            return
        }
        loadingDialog.show()
//        classList.forEach {
//            it.Layer = layer
//            it.SetID = setId
//            it.state = state
//        }
        viewModel.releaseAuditPaper(setId, Ext.GLOBAL_GRADE,
                CurrentUser.getToken(), mutableListOf(paperId), publishWindow.getStartTime(),
                publishWindow.getEndTime(),
                classList.toMutableList(), CurrentUser.getUserID(), CurrentUser.getSchoolID(), layer, -1,
                CurrentUser.getUserName())
    }

    fun setClass(name: String, position: Int) {
        if (classPosition == position) {
            return
        }
        classPosition = position
        classPopupWindow.adapter.apply {
            posList.forEach {
                posList[it.key] = false
            }
            posList[position] = true
            notifyDataSetChanged()
        }
        tv_classname.text = name
        initEffectiveInfo()
        initPaper()
    }

    private fun reSet() {
        filterPopupWindow.contentView.apply {
            (cg_finish.getChildAt(0) as Chip).isChecked = true
            (cg_type.getChildAt(0) as Chip).isChecked = true
        }
    }

    @SuppressLint("SetTextI18n")
    override fun startObserve() {
        viewModel.mEffectiveInfo.observe(this, Observer {
            tv_paper_num.text = HtmlUtils.setText(
                    "针对${Ext.COURSE_CLASSNAME}，您已发布${it.TotalPaperCount}份试卷，其中AI试卷<font color='#00afff'>${
                    it.AIPaperCount}</font>份，本地试卷<font color='#ff9900'>${it.LocalPaperCount}</font>份。")
            tv_coverrate.text =
                    "${if (it.CoverTotalZsdRate.isNotEmpty()) it.CoverTotalZsdRate else "--"}%"
            tv_matchrate.text = "${if (it.MatchRate.isNotEmpty()) it.MatchRate else "--"}%"
            if (it.Effective.isEmpty()) {
                return@Observer
            }
            if (Ext.STAGE_NO == "B") {
                if (it.Effective.toDouble() < 70f) tv_hint.text =
                        "建议您优先使用基础复习或校本化复习针对常考知识点发布复习试卷。"
                else {
                    tv_hint.text = "建议您可以使用拓展复习发布复习试卷，进行拔高训练。"
                }
            } else {
                if (it.Effective.toDouble() < 85f) tv_hint.text =
                        "建议您优先使用基础复习或校本化复习针对常考知识点发布复习试卷。"
                else {
                    tv_hint.text = "建议您可以使用拓展复习发布复习试卷，进行拔高训练。"
                }
            }
        })
        viewModel.mPaperTrailInfo.observe(this, Observer {
            paperList.clear()
            if (it.Count == 0) {
                group.visibility = View.GONE
                group2.visibility = View.VISIBLE
            } else {
                group.visibility = View.VISIBLE
                group2.visibility = View.GONE
            }
            it.List.forEach { paperTrail ->
                val sectionHeader = PaperTrailSection(true, paperTrail.CreateTime)
                paperList.add(sectionHeader)
                paperTrail.PaperList.forEach { paperTime ->
                    val section = PaperTrailSection(paperTime)
                    paperList.add(section)
                }
            }
            paperAdapter.setNewData(paperList)
            swipe_layout.finishRefresh()
            swipe_layout.setEnableLoadMore(viewModel.pageSize.value!! < it.Count)
            if (viewModel.pageSize.value!! == it.Count) {
                swipe_layout.finishLoadMoreWithNoMoreData()
            } else {
                swipe_layout.finishLoadMore()
            }
        })
        viewModel.success.observe(this, Observer {
            loadingDialog.dismiss()
            if (it.ReleaseResult) {
                publishWindow.dismiss()
                val publishDialog = PublishResultDialog().apply {
                    arguments = bundleOf().apply {
                        putParcelableArrayList("release", it.ClassEffectiveList)
                    }
                }
                publishDialog.show(parentFragmentManager, "")
                OperationHelp.operationLog(1, activity)
                initPaper()
            } else {
                MyToast.showToast("发布失败")
            }
        })
        viewModel.mEditDurationInfo.observe(this, Observer {
            editLoadingDialog.dismiss()
            when (it) {
                false -> {
                    MyToast.showToast("试卷已到期，无法修改作答期限")
                }
                true -> {
                    MyToast.showToast("修改成功")
                    timeEditWindow?.dismiss()
                    initPaper()
                }
            }
        })
        viewModel.mSubmittedInfo.observe(this, Observer {
            val stuProgressDialog = StuProgressDialog().apply {
                arguments = bundleOf(Pair("info", it), Pair("type", type))
            }
            stuProgressDialog.show(parentFragmentManager, "")
        })
        viewModel.mClassFlag.observe(this, Observer {
            classFlagList.clear()
            classFlagList.addAll(it)
            publishWindow.setOnDismissListener { dismissAnimation() }
            publishWindow.showAtLocation(tv_title, Gravity.BOTTOM, 0, 0)
            showAnimation()
        })
        viewModel.mHastenCall.observe(this, Observer {
            when (it) {
                0 ->  MyToast.showToast("催交作业失败")
                1 ->  MyToast.showToast("催交作业成功")
                else -> initPaper()
            }
        })
        viewModel.mErrorMsg.observe(this, Observer {
            loadingDialog.dismiss()
            editLoadingDialog.dismiss()
            MyToast.showToast(it)
        })
    }

    override fun onResume() {
        super.onResume()
        initEffectiveInfo()
        initPaper()
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (adapter) {
            is PaperTrailListAdapter -> {
                val paperId = adapter.data[position].t.PaperID
                val setId = adapter.data[position].t.SetID
                AibkPaperPreviewActivity.launch(requireActivity(), paperId, setId, false)
            }
            is ClassListAdapter -> {
                Ext.COURSE_CLASSNAME = Ext.INFOLIST!![position].CourseClassName
                MkUtils.encode("COURSE_CLASSNAME", Ext.COURSE_CLASSNAME)
                Ext.COURSE_CLASSID = Ext.INFOLIST!![position].CourseClassID
                MkUtils.encode("COURSE_CLASSID", Ext.COURSE_CLASSID)
                Ext.GLOBAL_GRADE = Ext.INFOLIST!![position].GlobalGrade
                MkUtils.encode("GLOBAL_GRADE", Ext.GLOBAL_GRADE)
                Ext.STAGE_NO = when (Ext.GLOBAL_GRADE) {
                    "K6", "K7", "K8", "K9" -> "B"
                    else -> "C"
                }
                setClass(Ext.COURSE_CLASSNAME, position)
                val commentsFragment = parentFragmentManager.findFragmentByTag(
                        "f1") as CommentsFragment
                commentsFragment.setClass(Ext.COURSE_CLASSNAME, position)
                classPopupWindow.dismiss()
            }
        }
    }

    @SuppressLint("SetTextI18n")

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val setId = paperList[position].t.SetID
        val paperId = paperList[position].t.PaperID
        val paperName = paperList[position].t.PaperName
        val layer = paperList[position].t.Layer
        val startTime = paperList[position].t.StartTime
        val endTime = paperList[position].t.EndTime
        val intent = Intent()
        intent.putExtra("setId", setId)
        intent.putExtra("paperId", paperId)
        intent.putExtra("layer", layer)
        when (view?.id) {
            R.id.tv_detail -> {
                if (paperList[position].t.State == 2) {
                    return
                }
                intent.putExtra("paperName", paperName)
                intent.setClass(requireActivity(), CheckScoreActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_comment -> {
                if (paperList[position].t.EvalCount == 0) {
                    return
                }
                AibkQuesMarkActivity.launch(requireActivity(), setId, "", paperId, paperName, false)
            }
            R.id.tv_publish -> {
                this.position = position
                viewModel.getGradeClassWithPaperState(Ext.GLOBAL_GRADE, CurrentUser.getSchoolID(), setId,
                        paperId, CurrentUser.getToken(), CurrentUser.getUserID())
            }
            R.id.tv_time -> {
                timeEditWindow =
                    AnswerTimeEditPopupWindow(requireContext(), startTime, endTime, this)
                timeEditWindow?.setOnDismissListener { dismissAnimation() }
                timeEditWindow?.showAtLocation(tv_title, Gravity.BOTTOM, 0, 0)
                showAnimation()
                this.position = position
                val item = adapter?.getViewByPosition(rv_paper,
                        position + adapter.headerLayoutCount, R.id.tv_time) as TextView
                timeEditWindow!!.contentView.tv_answerTime.text = "当前作答期限：${item.text}"
            }
            R.id.tv_submited, R.id.tv_total, R.id.tv_finished -> {
                type = 0
                viewModel.getStuProgress(paperId,
                        Ext.COURSE_CLASSID, CurrentUser.getSchoolID(), CurrentUser.getToken(),
                        CurrentUser.getUserID())
            }
            R.id.tv_commented, R.id.tv_comment_num, R.id.tv_comment_total_num -> {
                type = 1
                viewModel.getStuProgress(
                        paperId,
                        Ext.COURSE_CLASSID, CurrentUser.getSchoolID(), CurrentUser.getToken(),
                        CurrentUser.getUserID())
            }
            R.id.iv_hastencall -> viewModel.doHastenCall(CurrentUser.getToken(), CurrentUser.getUserID(),
                    paperId, setId, Ext.COURSE_CLASSID, paperName, CurrentUser.getSchoolID())
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_textbook -> startActivity(
                    Intent(requireContext(), BasicPaperActivity::class.java).apply {
                        putExtra("layer", 3)
                    })
            R.id.tv_topic -> startActivity(
                    Intent(requireContext(), BasicPaperActivity::class.java).apply {
                        putExtra("layer", 4)
                    })
            R.id.tv_test -> startActivity(
                    Intent(requireContext(), BasicPaperActivity::class.java).apply {
                        putExtra("layer", -2)
                    })
            R.id.tv_library -> startActivity(
                    Intent(requireContext(), BasicPaperActivity::class.java).apply {
                        putExtra("layer", 6)
                    })
            R.id.tv_local -> startActivity(
                    Intent(requireContext(), PaperLibraryActivity::class.java))
            R.id.tv_reset -> reSet()
            R.id.tv_done -> {
                filterPopupWindow.dismiss()
                initPaper()
            }
            R.id.tv_filter -> {
                nsv.scrollTo(0, textView2.top - 10)
                filterPopupWindow.setOnDismissListener { dismissAnimation() }
                filterPopupWindow.showAsDropDown(textView2, 0, 10)
                showAnimation()
            }
            R.id.iv_cancel -> publishWindow.dismiss()
            R.id.tv_publish -> {
                if (publishWindow.getEndTime() < publishWindow.getStartTime()) {
                    MyToast.showToast("结束时间不得小于开始时间")
                    return
                }
                release(position)
            }
            R.id.iv_close -> timeEditWindow?.dismiss()
            R.id.tv_confirm -> {
                if (timeEditWindow!!.getEndTime() < timeEditWindow!!.getStartTime()) {
                    MyToast.showToast("结束时间不得小于开始时间")
                    return
                }
                editLoadingDialog.show()
                viewModel.setPaperAnswerDuration(paperList[position].t.PaperID, Ext.COURSE_CLASSID,
                        timeEditWindow!!.getStartTime(),
                        timeEditWindow!!.getEndTime(), CurrentUser.getToken(),
                        CurrentUser.getSchoolID(), paperList[position].t.SetID, Ext.GLOBAL_GRADE,
                        CurrentUser.getUserID())
            }
            R.id.tv_classname -> {
                classPopupWindow.setOnDismissListener {
                    dismissAnimation()
                }
                classPopupWindow.showAsDropDown(binding.tvClassname, -100, 10)
                showAnimation()
            }
        }
    }


    override fun onCheckedChanged(group: ChipGroup?, checkedId: Int) {
        when (checkedId) {
            R.id.cp_finish_all -> finish = -1
            R.id.cp_unfinished -> finish = 0
            R.id.cp_finished -> finish = 1
            R.id.cp_type_all -> layer = -1
            R.id.cp_type_textbook -> layer = 3
            R.id.cp_type_topic -> layer = 4
            R.id.cp_type_basic -> layer = 0
            R.id.cp_type_expand -> layer = 1
            R.id.cp_type_model -> layer = 2
            R.id.cp_type_local -> layer = 5
            R.id.cp_type_school -> layer = 6
        }
    }
}